<template>
  <el-card shadow="hover">
    <div slot="header" class="clearfix">
      <span>{{ title }}</span>
      <el-button style="float: right" size="small" @click="$emit('cancel')"
        >返回</el-button
      >
    </div>
    <div>
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-position="right"
        label-width="100px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="登录用户名" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入登录名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="密码"
              prop="password"
              v-if="this.form.id == null"
            >
              <el-input
                v-model="form.password"
                type="password"
                placeholder="请输入登录密码"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select
                v-model="form.sex"
                placeholder="请选择性别"
                style="width: 80%"
              >
                <el-option :value="0" label="男" />
                <el-option :value="1" label="女" />
                <el-option :value="2" label="未知" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入用户昵称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="微信唯一id" prop="openId">
              <el-input v-model="form.openId" placeholder="请输入微信唯一id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户角色" prop="roles">
              <el-select
                v-model="rolesId"
                placeholder="请选择角色"
                style="width: 80%"
                multiple
              >
                <el-option
                  v-for="(item, index) in roleList"
                  :key="index"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="status">
              <el-radio-group v-model="form.status" class="status-class">
                <el-radio border :label="true">是</el-radio>
                <el-radio border :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户头像" prop="avatar">
              <!--
                                 action: 上传地址
                                 show-file-list： 是否展示列表
                                 on-success：
                             -->
              <el-upload
                class="avatar-uploader"
                v-model="form.avatar"
                :action="action"
                :headers="headers"
                :show-file-list="false"
                :on-success="handleSuccess"
                :before-upload="beforeUpload"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="address">
              <el-input
                v-model="form.address"
                type="textarea"
                placeholder="请输入地址"
                show-word-limit
                maxlength="100"
                :autosize="{ minRows: 2, maxRows: 5 }"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="float: right; margin-top: -80px">
          <el-col>
            <el-col :span="24">
              <el-form-item label="超级管理员" prop="status">
                <el-radio-group v-model="form.admin" class="status-class1">
                  <el-radio border :label="true">是</el-radio>
                  <el-radio border :label="false">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="$emit('cancel')">取 消</el-button>
        <el-button type="primary" @click="clickOk">确 定</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
import { isEmail } from "@/utils/validate";
export default {
  /** 接受父组件传递的值 */
  props: ["title", "form"],
  /** 属性监听 回显*/
  watch: {
    form: {
      handler(val, old) {
        this.rolesId = [];
        console.log("表单值", val);
        this.form.userName = val.name;
        this.imageUrl = val.avatar.startsWith("https")
          ? val.avatar
          : this.$qiniu + val.avatar;
        // 回显角色信息
        if (val.roles && val.roles.length > 0) {
          val.roles.forEach((item) => {
            this.rolesId.push(item.id);
          });
        }
      },
    },
  },
  data() {
    return {
      // 表单校验规则
      rules: {
        userName: [
          { required: true, message: "请输入登录名", trigger: "blur" },
          {
            min: 2,
            max: 30,
            message: "登录名称的长在2 ~ 30 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入登录密码", trigger: "blur" },
          {
            min: 6,
            max: 100,
            message: "登录密码的长在6 ~ 30 个字符",
            trigger: "blur",
          },
        ],
        sex: [
          {
            required: true,
            // 自定义校验规则 使用匿名函数
            validator: (rule, value, callback) => {
              if (this.form.sex === undefined || this.form.sex === null) {
                callback(new Error("请选择性别"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        avatar: [
          {
            required: true,
            // 自定义校验规则 使用匿名函数
            validator: (rule, value, callback) => {
              if (!this.form.avatar) {
                callback(new Error("请上传头像"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        openId: [
          { required: true, message: "请输入登录名", trigger: "blur" },
          {
            min: 2,
            max: 30,
            message: "角色名称的长在2 ~ 30 个字符",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: false,
            validator: (rule, value, callback) => {
              if (!isEmail(value)) {
                callback(new Error("邮箱格式错误"));
              } else {
                callback();
              }
            },
          },
        ],
      },
      imageUrl: null,
      action: "/tool/upload",
      headers: {
        Authorization: sessionStorage.getItem("token"),
      },
      roleList: [],
      rolesId: [],
    };
  },
  created() {
    this.$ajax.get("/role/findAll").then((res) => {
      this.roleList = res.data.data;
      console.log("打印", this.roleList);
    });
  },
  methods: {
    /**
     * 上传成功
     * res: 返回的参数
     * file: 上传文件信息
     * */
    handleSuccess(res, file) {
      this.imageUrl = this.$qiniu + res.data;
      this.form.avatar = res.data;
    },
    /**
     * 上传之前
     * file: 可以判断文件类型、文件大小
     * */
    beforeUpload(file) {
      /* 判断文件大小 不能超过10m */
      if (file.size > 10 * 1024 * 1024) {
        this.$message.warning("上传图片大小不能超过10M!");
        return false;
      }
      /* 判断文件类型 */
      // 定义索引 到最后一个点的位置
      let index = file.name.lastIndexOf(".");
      // 截取后缀
      let hz = file.name.substring(index + 1);
      if (hz !== "jpg" && hz !== "png" && hz !== "PNG" && hz !== "jpeg") {
        this.$message.warning("请上传-jpg-png-jpeg-格式的图片!");
        return false;
      }
    },
    /** 点击确定 */
    clickOk() {
      // 进行表单校验
      this.$refs.form.validate((valid) => {
        // 校验不通过
        if (!valid) return this.$message.error("表单校验失败,请检查后提交！");
        let arr = [];
        this.rolesId.forEach((item) => {
          arr.push({ id: item });
        });
        this.form.roles = arr;
        // 校验通过
        console.log(this.form);
        if (!this.form.id) {
          this.$ajax.post("/sysUser/insert/", this.form).then((res) => {
            this.$message.success(res.data.message);
            return this.$emit("cancel");
          });
        } else {
          this.$ajax.put("/sysUser/update/", this.form).then((res) => {
            this.$message.success(res.data.message);
            return this.$emit("cancel");
          });
        }
      });
    },
  },
};
</script>

<style scoped>
.status-class {
  margin-left: -55%;
}
.status-class1 {
  margin-left: 0px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 20px;
  color: #8c939d;
  width: 130px;
  height: 130px;
  line-height: 130px;
  text-align: center;
}
.avatar {
  width: 130px;
  height: 130px;
  display: block;
}
.clearfix {
  text-align: left;
  margin-left: 20px;
}
</style>
